<template>
  <div>
    <el-dialog v-bind="$attrs" v-on="$listeners"
               @open="onOpen" @close="onClose"
               :title="isEdit ? (isSelf ? '房屋信息-编辑' : '编辑房屋') : '添加房屋'" :visible.sync="showDialog"
               :close-on-click-modal="false">
      <el-row :gutter="0">
        <el-form ref="HouseInfoForm" :model="formData" size="small" label-width="98px">
          <el-col :span="12">
            <el-form-item label="房屋视频">
              <el-upload
                class="upload-demo"
                :action="this.fileUpload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                multiple
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="fileList">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传mp4文件，且不超过50mb</div>
              </el-upload>
              <!--              <el-upload-->
              <!--                accept="image/*"-->
              <!--                class="avatar-uploader"-->
              <!--                :action="fileUpload"-->
              <!--                :auto-upload="true"-->
              <!--                :headers="headerObject"-->
              <!--                :show-file-list="false"-->
              <!--                :on-success="handleAvatarSuccess"-->
              <!--                :before-upload="beforeAvatarUpload">-->
              <!--                <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="暂无">-->
              <!--                <i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
              <!--              </el-upload>-->
            </el-form-item>
            <el-form-item label="省">
              <el-select v-model="valueProvince" placeholder="选择省" @change="changeProvince" :style="{width: '100%'}">
                <el-option v-for="item in provinceOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="市">
              <el-select v-model="valueCity" placeholder="选择市" @change="changeCity" clearable :style="{width: '100%'}">
                <el-option v-for="item in cityOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="区/县">
              <el-select v-model="valueOrigin" placeholder="选择区/县" @change="changeOrigin" clearable :style="{width: '100%'}">
                <el-option v-for="item in originOptions" :key="item.label" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="详细地址" prop="addressInfo">
              <el-input v-model="formData.addressInfo" placeholder="请输入详细地址" :maxlength="50" show-word-limit
                        clearable prefix-icon='el-icon-s-home' :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input v-model="formData.price" placeholder="请输入价格" :maxlength="6" show-word-limit
                        clearable prefix-icon='el-icon-goods' :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="描述" prop="houseDescribe">
              <el-input v-model="formData.houseDescribe" placeholder="请输入房屋描述" clearable prefix-icon='el-icon-video-camera'
                        :style="{width: '100%'}" maxlength="50" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="房屋类型" prop="houseType">
              <el-select clearable v-model="formData.houseType" placeholder="请选择" :style="{width: '100%'}">
                <el-option label="商品房" :value="0"></el-option>
                <el-option label="单身公寓住宅" :value="1"></el-option>
                <el-option label="单元式住宅" :value="2"></el-option>
                <el-option label="复式住宅" :value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="房屋户型" prop="decorateState">
              <el-select clearable v-model="formData.houseLayout" placeholder="请选择" :style="{width: '100%'}">
                <el-option label="一室一厅" :value="0"></el-option>
                <el-option label="两室一厅" :value="1"></el-option>
                <el-option label="三室一厅" :value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="面积㎡" prop="area">
              <el-input v-model="formData.area" placeholder="请输入面积" :maxlength="5" clearable prefix-icon='el-icon-magic-stick'
                        :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="租期" prop="leaseTerm" >
              <el-select clearable v-model="formData.leaseTerm" placeholder="请选择" :style="{width: '100%'}">
                <el-option label="三月" :value="90"></el-option>
                <el-option label="半年" :value="180"></el-option>
                <el-option label="一年" :value="360"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="装修情况" prop="decorateState">
              <el-select clearable v-model="formData.decorateState" placeholder="请选择" :style="{width: '100%'}">
                <el-option label="精美装修" :value="0"></el-option>
                <el-option label="简单装修" :value="1"></el-option>
                <el-option label="毛坯装修" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer">
        <el-button @click="onClose" type="danger" icon="el-icon-close" size="small">取 消</el-button>
        <el-button @click="handelConfirm" type="success" icon="el-icon-upload2" size="small" :disabled="isSubmit">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { addHouseInfo, getHouseInfoById, editHouseInfo } from '@/api/houseInfo'
  import { areaList } from '@/utils/provices'

  export default {
    name: 'AddOrUpdate',
    data () {
      // 数据
      return {
        url:'',
        fileList: [],
        areaList: areaList,
        valueProvince: null,
        valueCity: null,
        valueOrigin: null,
        provinceOptions: [], // 省列表
        cityOptions: [], // 市下拉框数据
        originOptions: [], // 区下拉框数据
        formData: {
          address: undefined,
          addressInfo: undefined,
          price: undefined,
          avatar: '',
          houseDescribe: undefined,
          houseType: undefined,
          houseLayout:undefined,
          area: null,
          leaseTerm: undefined,
          decorateState: undefined
        },
        showDialog: false,
        imageUrl: require('@/assets/img/default.jpg'),
        fileUpload: '',
        isSubmit: false,
        // headerObject: {
        //   Authorization: window.sessionStorage.getItem('token')
        // } // 图片上传请求头
      }
    },
    props: {
      addOrUpdateVisible: {
        type: Boolean,
        default: false
      },
      id: {
        type: Number,
        default: 0
      },
      isEdit: {
        type: Boolean,
        default: false
      },
      isSelf: {
        type: Boolean,
        default: false
      }
    },
    computed: {},
    watch: {
      // 监听 addOrUpdateVisible 改变
      addOrUpdateVisible () {
        this.showDialog = this.addOrUpdateVisible
      }
    },
    created () {
      this.buildProvesData()
    },
    methods: {
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file.response);
        this.url=file.response.data.url
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      onOpen () {
        this.fileUpload = process.env.VUE_APP_UPLOADMP4_URL
        if (this.isEdit) {
          // 根据userId查找用户信息
          const _this = this
          getHouseInfoById(this.id).then(response => {
            // 获取到用户信息，填充至各个字段的值当中去
            _this.formData = response.data
            const strs = this.formData.address.split('/')
            this.valueProvince = strs[0]
            this.valueCity = strs[1]
            this.valueOrigin = strs[2]
            if (_this.formData.avatar !== '') {
              _this.imageUrl = _this.formData.avatar
            }
          })
        } else {
          // 不是编辑框，将 form 表单信息清除
          this.resetFormData()
        }
      },
      onClose () {
        this.imageUrl = require('@/assets/img/default.jpg')
        // 清除 rule 数据
        this.$refs.HouseInfoForm.clearValidate()
        this.$emit('changeShow', 'false')
      },
      handelConfirm () {
        this.$refs.HouseInfoForm.validate(valid => {
          // 验证不通过
          if (!valid) return
          const _this = this
          _this.isSubmit = true
          // 判断是新增还是修改
          if (!_this.isEdit) {
            _this.formData.avatar=this.url
            _this.formData.address = _this.valueProvince + '/' + _this.valueCity + '/' + _this.valueOrigin
            addHouseInfo(_this.formData).then(response => {
              _this.RightMessage(_this, '成功', response.message, 'success')
              _this.$emit('update:visible', false)
              // 关闭展示框
              _this.$emit('changeShow', 'false')
              _this.$emit('dataUpdate')
            }).finally(() => {
              _this.isSubmit = false
            })
          } else {
            editHouseInfo(_this.formData, _this.id).then(response => {
              // 如果是当前登录用户，需要更新 sessionStorage 的数据
              if (_this.isSelf) {
                window.sessionStorage.setItem('account', JSON.stringify(_this.formData))
                _this.RightMessage(_this, '成功', response.message + '，请刷新页面！', 'success')
              } else {
                _this.RightMessage(_this, '成功', response.message, 'success')
              }
              _this.$emit('update:visible', false)
              _this.$emit('changeShow', 'false')
              _this.$emit('dataUpdate')
            }).finally(() => {
              _this.isSubmit = false
            })
          }
        })
      },
      // beforeAvatarUpload (file) {
      //   const isJPG = file.type === 'image/jpeg'
      //   const isLt2M = file.size / 1024 / 1024 < 2
      //   if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 JPG 格式!')
      //   }
      //   if (!isLt2M) {
      //     this.$message.error('上传头像图片大小不能超过 2MB!')
      //   }
      //   return isJPG && isLt2M
      // },
      resetFormData () {
        this.fileList=[]
        this.formData.address = undefined
        this.formData.addressInfo = undefined
        this.formData.price = undefined
        this.formData.avatar = ''
        this.formData.houseDescribe = undefined
        this.formData.houseType = undefined
        this.formData.area = null
        this.formData.leaseTerm = undefined
        this.formData.decorateState = undefined
      },
      // handleAvatarSuccess (res, file) {
      //   if (res.code === 200) {
      //     this.imageUrl = URL.createObjectURL(file.raw)
      //     this.formData.avatar = res.data
      //   } else {
      //     this.$message.error(res.message)
      //   }
      // },
      changeProvince (val) {
        this.valueCity = ''
        this.valueOrigin = ''
        this.cityOptions = []
        this.originOptions = []
        this.provinceOptions.forEach((province) => {
          if (val.toString() === province.value) {
            this.valueProvince = province.label
            this.cityOptions = province.children
          }
        })
      },
      changeCity (val) {
        this.valueOrigin = ''
        this.originOptions = []
        this.cityOptions.forEach((city) => {
          if (val.toString() === city.value) {
            this.valueCity = city.label
            this.originOptions = city.children
          }
        })
      },
      changeOrigin (val) {
        this.originOptions.forEach((origin) => {
          if (val.toString() === origin.value) {
            this.valueOrigin = origin.label
          }
        })
        this.$forceUpdate()
      },
      /**
       * 构造省市县下拉框数据
       */
      buildProvesData () {
        // 构造省数据
        const provinces = this.areaList.province_list
        for (const value in provinces) {
          this.provinceOptions.push({
            value: value,
            label: provinces[value],
            children: []
          })
        }

        // 构造市数据
        const cities = this.areaList.city_list
        this.provinceOptions.forEach(province => {
          for (const city in cities) {
            if (province.value.substr(0, 2) === city.substr(0, 2)) {
              province.children.push({
                value: city,
                label: cities[city],
                children: []
              })
            }
          }
        })

        // 构造区县数据
        const counties = this.areaList.county_list
        this.provinceOptions.forEach(province => {
          province.children.forEach(city => {
            for (const county in counties) {
              if (city.value.substr(0, 4) === county.substr(0, 4)) {
                city.children.push({
                  value: county,
                  label: counties[county],
                  children: []
                })
              }
            }
          })
        })
      },
    }
  }
</script>
<style>

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
